import { Button, Form, Input, Card, message } from 'antd';
import { addBannerApi } from '@/api/banner';
import { useNavigate } from '@umijs/max';
// import { context } from '@/layouts/index';
// import { useContext } from 'react';

let img: string;

const Index = () => {
  // const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  // const { api } = useContext(context);

  const onFinish = async (values: any) => {
    // console.log('Success:', { ...values, img: img });
    const res = await addBannerApi({ ...values, img: img });
    if (res) {
      // api.open({
      //   type: 'success',
      //   content: '上传成功',
      // });
      message.success('上传成功');
      navigate('/banner/list');
    }
  };

  const fileChange = (e: any) => {
    // console.log(e.target.files[0]);
    // 转成base64的形式
    const reader = new FileReader();
    reader.readAsDataURL(e.target.files[0]);
    reader.onload = (event: any) => {
      console.log(event.target.result);
      img = event.target.result;
      console.log(img);
    };
  };

  return (
    <Card>
      {/* {contextHolder} */}
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="link"
          name="link"
          rules={[{ required: true, message: 'Please input your link!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="alt"
          name="alt"
          rules={[{ required: true, message: 'Please input your alt!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="image"
          name="img"
          rules={[{ required: true, message: 'Please input your image!' }]}
        >
          <Input type="file" onChange={fileChange} />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default Index;
